# from pathlib import Path
#
# total=0
# for i in Path.cwd().parent.rglob('*.py'):
#     print(i)
#     with open(i,'r',encoding='utf-8') as f:
#         num=len(f.read())
#         total+=num
# print(total)

# with open('data.txt', 'a', encoding='utf-8') as f:
#     f.write('床前明月光')

# user_name=str(input('请输入您的文件名：'))
# with open(user_name+'.txt','w',encoding='utf-8') as f:
#     user_content=input('请输入您要输入的内容：')
#     f.write(user_content)

# with open('a.txt', 'a', encoding='utf-8') as f:
#     a_copy=f.read()
# with open(a_copy+'.txt', 'a+', encoding='utf-8') as f:
#     print(a_copy)

# try:
#     with open('nonexistent.txt', 'r') as f:
#         content = f.read()
# except FileNotFoundError:
#     print("文件不存在")
# except IOError:
#     print("IO错误")
# else:
#     print("读取成功")
# finally:
#     print("清理完成")

def read_file_safely(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return f.read()
    except UnicodeDecodeError:
        try:
            with open(filename, 'r', encoding='gbk') as f:
                return f.read()
        except:
            return "解码失败"
    except Exception as e:
        return f"错误: {e}"

print(read_file_safely('nonexistent.txt'))


